<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Admin\Models\StoreMemberCards;
use App\Admin\Models\Common;
use App\Admin\Models\StoreCardsLog;
use App\Services\Store;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Encore\Admin\Facades\Admin;
use Illuminate\Support\Facades\Input;
use Illuminate\Http\Request as Req;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\MessageBag;
use Ixudra\Curl\Facades\Curl;
use DB;

class StoreMemberCardsController extends Controller
{
	use HasResourceActions;
	
    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('会员卡项')
            ->description('列表')
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('会员')
            ->description('详细')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('会员')
            ->description('编辑')
            ->body($this->form()->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('会员')
            ->description('创建')
            ->body($this->form());
    }
    
//  public function update(Request $request, $id)
//  {
//
//  }
    
//  /**
//   * Handle update.
//   *
//   * @param int $id
//   *
//   * @return \Symfony\Component\HttpFoundation\Response
//   */
//  public function update($id, $data = null)
//  {	
//  	
//      return $this->returnMsg(1, $id);
//  }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new StoreMemberCards);

        $grid->smcId('ID');
        $grid->sgName('卡包名称');
        $grid->smcCanUseNum('剩余次数')->display(function ($smcCanUseNum) {
        	
        	if ($smcCanUseNum == 0){
        		$grayScript = <<<EOT

	$('#sign{$this->smcId}').parent().parent().css({"background": "#CCCCCC"});

EOT;
				Admin::script($grayScript);
        	}
        	return '<input type="hidden" id="sign'.$this->smcId.'">'."<a id='' class='btn btn-dropbox' href='".route('cardUseList')."?smcId={$this->smcId}'>{$this->smcCanUseNum}</a>";
		});
        
        $grid->muNickName('会员姓名');
        $grid->createTime('购买时间');
		$grid->expDate('到期时间');

		$grid->filter(function($filter){

		    // 去掉默认的id过滤器
		    $filter->disableIdFilter();

		});
		
		$grid->actions(function ($actions) {
		    $actions->disableDelete();
//		    $actions->disableEdit();
				$row = $actions->row;
				if ($row['expDate']!='' && date("Y-m-d") > $row['expDate']) {
					$actions->disableEdit();
				}
		    $actions->disableView();
		});

		$grid->filter(function($filter){

		    // 去掉默认的id过滤器
		    $filter->disableIdFilter();
		});
		
		// 禁用创建按钮
		$grid->disableCreateButton();

		// 默认展开筛选框
//		$grid->expandFilter();
		
		// 禁用行选择checkbox
		$grid->disableRowSelector();
		
		// 禁用导出
		$grid->disableExport();
		
        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
    	$Member = new Member();
        $show = new Show($Member->findOrFail($id));

        $show->muId('ID');
        $show->muCode('用户码');
        $show->muNickName('昵称');
        $show->muRealName('姓名');
        $show->muSex('性别')->using(['0' => '女', '1' => '男']);;
        $show->muMobile('手机号');
        $show->muMemo('备注');
//      $show->muAccount('账户金额');
        $show->muPoints('积分');
        $show->muTotalExpend('总消费');
        $show->createTime('创建时间');
        $show->updateUser('最后修改人');
        $show->updateTime('最后修改时间');

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::Form(StoreMemberCards::class, function (Form $form) {
			
			$sId = Admin::user()->sId;
			
			$form->hidden('smcId');
			$form->hidden('sgShuiguangCard');
			$form->text('sgName', '卡包')->readOnly();
			$form->text('muNickName', '会员姓名')->readOnly();
			$id = isset(request()->route()->parameters()['storeMemberCard']) ? request()->route()->parameters()['storeMemberCard'] : null;
			if($id >0){
				$StoreMemberCards = new StoreMemberCards();
				$model = $StoreMemberCards->findOrFail($id);
			}else{
				$model=0;
			}
			
			if($model && $model->expDate != ''){
				$form->display('expDate', '到期时间')->rules(function ($form) {
					// 如果不是编辑状态，则添加字段唯一验证
					if ($form->model() && $form->model()->expDate!='' && date("Y-m-d") > $form->model()->expDate) {
						return '年卡已过期';
					}else{
						return array('required',array('required'=>'年卡已过期'));
					}
				});
			}else{
				if($model && $model->sgShuiguangCard==1){
					$form->display('smcCanUseNum', '产品剩余次数');
				}else{
					$form->display('smcCanUseNum', '服务剩余次数');
				}
			}
			
        	$form->select('auCode', '本次服务店员')->options($this->common->getReferrerSelect($sId))
        										->rules("required", ['required' => '请选择服务店员']);
        	if($model->sgShuiguangCard != 1){
				//$form->number('subNum', '本次消耗')->default(1)->rules('required|regex:/^\d+$/', ['regex' => '必须为数字']);
				$sclPartsArray = ['活氧气泡焕肤','纳米微晶活肤洁净（祛角质）','雪肌玉肤面部焕颜（嫩肤白皙）','冰肌紧致脸部提拉','阿米肩颈流通护理','阿米眼部活力护理','阿米头部经络疏通护理','阿米固本肝肾护理','阿米回春卵巢护理','阿米脉能臀疗护理','塑形小蛮腰','紫草干细胞原液水光','淋巴机器人健康管理','魔指丰胸','纤美极减肥塑形','腿部经络疏通','肠胃保养'];
				$sclPartsSelect = array();
				foreach($sclPartsArray as $sclPart){
					$sclPartsSelect[$sclPart] = $sclPart;
				}
				$form->multipleSelect('sclParts', '服务项目')->options($sclPartsSelect);
			}else{
				$form->text('subNum', '本次消耗')->default(1)->readOnly();
			}
        	$states = [
			    'on'  => ['value' => 1, 'text' => '是', 'color' => 'success'],
			    'off' => ['value' => 0, 'text' => '否', 'color' => 'danger'],
			];
        	$form->switch('isGetMoney', '是否已领取服务费')
				 ->states($states)
				 ->default(0);
//				 ->readOnly();
        	$form->text('createTime', '购卡时间')->readOnly();

            $form->tools(function (Form\Tools $tools) {

			    // 去掉`列表`按钮
				//$tools->disableList();
			    // 去掉`删除`按钮
			    $tools->disableDelete();
			
			    // 去掉`查看`按钮
			    $tools->disableView();
			
			    // 添加一个按钮, 参数可以是字符串, 或者实现了Renderable或Htmlable接口的对象实例
//			    $tools->add('<a class="btn btn-sm btn-danger"><i class="fa fa-trash"></i>&nbsp;&nbsp;delete</a>');
			});
			
			$form->footer(function ($footer) {

//			    // 去掉`重置`按钮
			    $footer->disableReset();
//			
//			    // 去掉`提交`按钮
//			    $footer->disableSubmit();
			
			    // 去掉`查看`checkbox
			    $footer->disableViewCheck();
			
			    // 去掉`继续编辑`checkbox
			    $footer->disableEditingCheck();
			
			    // 去掉`继续创建`checkbox
			    $footer->disableCreatingCheck();
			
			});
			$form->saving(function ($form) {

				if($form->model()->subNum > $form->model()->smcCanUseNum){
					$error = new MessageBag([
						'title'   => '保存失败',
						'message' => '目前最多可使用'.$form->model()->smcCanUseNum.'次',
					]);		
					return back()->with(compact('error'));
				}
			});
        });
    }
    
    public function cardUseList(Content $content){

		$smcId = Request::get('smcId', false);

    	$grid = new Grid(new StoreCardsLog);

		if (!$smcId){
			// 结算
			$grid->sclId('ID');
	        $grid->sclUseNum('使用次数');
	        $grid->name('服务店员');
	        $grid->sclParts('服务内容');
	        $grid->muNickName('客户姓名');
	        $grid->sclIsGetTip('是否发放服务费')->display(function ($sclIsGetTip) {
	        	if ($sclIsGetTip){
	        		return '<span id="sclIsGetTip'.$this->sclId.'" class="label label-success">是</span><input id="servicePrice'.$this->sclId.'" type="hidden" value="'.$this->sgServiceMoney.'" />';
	        	}else{
	        		return '<span id="sclIsGetTip'.$this->sclId.'" class="label label-warning">否</span><input id="servicePrice'.$this->sclId.'" type="hidden" value="'.$this->sgServiceMoney.'" />';
	        	}
			    
			});
	        $grid->createTime('记录时间');
	        $grid->createUser('记录人');
			
			if (!isset($_GET['muCode'])){
				// 添加批量提交按钮
				$grid->tools(function (Grid\Tools $tools) {
				
				    $tools->append('<button id="settleTip" class="btn btn-sm btn-warning form-history-bac" style="float: right;margin-left: 25px;">结算服务费</button>');
				
					////////////////////////////
					$url = route('settleTip');
					$hideScript = <<<EOT
	
$("#settleTip").click(function(){

	var reqMax = 0;
	var reqIndex = 0;
	
	for(var i=0;i<$(".grid-row-checkbox").length;i++){
		if($(".grid-row-checkbox")[i].checked){
			reqMax++;
		}
	}
	
	for(var i=0;i<$(".grid-row-checkbox").length;i++){
		if($(".grid-row-checkbox")[i].checked){
			var id = $(".grid-row-checkbox")[i].dataset.id;
			$.get("{$url}?sclId="+id, function(result){
			    reqIndex++;
			    if (reqMax == reqIndex){
			    	window.location.reload();
			    }
			});
		}
	}
});

window.setInterval(function(){
	var reqMax = 0;
	var reqIndex = 0;
	
	var payPrice = 0;
	for(var i=0;i<$(".grid-row-checkbox").length;i++){
		if($(".grid-row-checkbox")[i].checked){
			var id = $(".grid-row-checkbox")[i].dataset.id;
			if ($("#sclIsGetTip"+id).html() == '否'){
				payPrice = payPrice + Number($("#servicePrice"+id).val())
			}
		}
	}

	$('#servicePayTotal').html(payPrice);
	return true;
}, 500);

EOT;
					Admin::script($hideScript);
					///////////////////////////
				});
				
				$grid->footer(function ($query) {
				    return "<div style='padding: 10px;'>总结算费用 ： <strong id='servicePayTotal' style='color: red;'>0</strong></div>";
				});
			}
			
			if (isset($_GET['muCode'])){
				// 禁用行选择checkbox
				$grid->disableRowSelector();
			}
			
			$grid->actions(function ($actions) {
			    $actions->disableDelete();
			    $actions->disableEdit();
			    $actions->disableView();
			});
			
			$grid->disableFilter();
			
			$grid->disableExport();
			
			// 禁用创建按钮
			$grid->disableCreateButton();
			
			return $content
	            ->header('卡项使用记录')
	            ->description('列表')
	            ->body($grid);
		}


        $grid->sclId('ID');
        $grid->sclUseNum('使用次数');
        $grid->name('服务店员');
        $grid->sclParts('服务内容');
        $grid->createTime('记录时间');
        $grid->createUser('记录人');
		
		$grid->actions(function ($actions) {
		    $actions->disableDelete();
		    $actions->disableEdit();
		    $actions->disableView();
		});

		$grid->filter(function($filter){

		    // 去掉默认的id过滤器
		    $filter->disableIdFilter();
		});
		
		// 禁用创建按钮
		$grid->disableCreateButton();

		// 默认展开筛选框
//		$grid->expandFilter();
		
		// 禁用行选择checkbox
		$grid->disableRowSelector();
		
		$grid->tools(function (Grid\Tools $tools) {
		
		    $tools->append('<a class="btn btn-sm btn-default form-history-bac" style="float: right;margin-right: 20px;" href="#" onClick="javascript :history.back(-1);"><i class="fa fa-arrow-left"></i>&nbsp;返回</a>');
		});
		
		// 禁用导出
//		$grid->disableExport();
		
		return $content
            ->header('卡项使用记录')
            ->description('列表')
            ->body($grid);
    }
    
    public function cardSellList(Content $content){
    	
    	$grid = new Grid(new StoreCardsLog);

        $grid->sclId('ID');
        $grid->sclUseNum('使用次数');
        $grid->username('服务店员');
        $grid->createTime('记录时间');
        $grid->createUser('记录人');
		
		$grid->actions(function ($actions) {
		    $actions->disableDelete();
		    $actions->disableEdit();
		    $actions->disableView();
		});

		$grid->filter(function($filter){

		    // 去掉默认的id过滤器
		    $filter->disableIdFilter();
		});
		
		// 禁用创建按钮
		$grid->disableCreateButton();

		// 默认展开筛选框
//		$grid->expandFilter();
		
		// 禁用行选择checkbox
		$grid->disableRowSelector();
		
		$grid->tools(function (Grid\Tools $tools) {
		
		    $tools->append('<a class="btn btn-sm btn-default form-history-bac" style="float: right;margin-right: 20px;" href="#" onClick="javascript :history.back(-1);"><i class="fa fa-arrow-left"></i>&nbsp;返回</a>');
		});
		
		// 禁用导出
//		$grid->disableExport();
		
		return $content
            ->header('卡项使用记录')
            ->description('列表')
            ->body($grid);
    }
    
    // 结算服务费用
    public function settleTip(Req $request){
    	
    	$TIP_MONEY = 18;
    	$sclId = $request->sclId;

    	$sclInfo = DB::Table('store_cards_log')
    				->leftJoin('store_goods', 'store_cards_log.sgId', '=', 'store_goods.sgId')
    				->where('store_cards_log.sclId', $sclId)
    				->where('store_cards_log.sclIsGetTip', 0)
    				->first();
    	
    	if(empty($sclInfo)){
    		return $this->returnMsg(0, '找不到对象或已经结算');
    	}
    	
    	$TIP_MONEY = $sclInfo->sgServiceMoney;
    	
    	DB::Table('store_cards_log')->where('sclId', $sclId)->update(['sclIsGetTip'=>1]);
    	
    	$sId = Admin::user()->sId;
    	$createUser = Admin::user()->name;
    	
    	$sInfo = DB::Table('store')->where('sId', $sId)->first();
    	
    	$Store = new Store();
    	// 减少店铺账
    	$Store->addWalletTrade($sId, 'paySettleTip', $sclId, '支付服务费结算', $createUser,
									$sInfo->sCode, -1*$TIP_MONEY, '', 0, -1*$TIP_MONEY);
		// 增加店员账				
		$Store->addWalletTrade($sId, 'getSettleTip', $sclId, '店铺服务费结算', $createUser,
									$sclInfo->auCode, $TIP_MONEY, '', 0, 0);
			
		// 对应统计
		$Store->addStatsDay($sId, $sInfo->sCode, 'profit', -1*$TIP_MONEY, 'paySettleTip');
		
		return $this->returnMsg(1, 'OK');
    }
}
